//
//  CNMainTabBar.swift
//  Ccweibo
//
//  Created by 陈锦聪 on 16/3/19.
//  Copyright © 2016年 Coco. All rights reserved.
//

import UIKit

let TabBarItemCount = 5

class CNMainTabBar: UITabBar {
    /// 回调闭包
    var composeClosure: (() -> ())?
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let width = frame.width / CGFloat(TabBarItemCount)
        
        let originFrame = CGRect(x: 0, y: 0, width: width, height: frame.height)
        
        let cls = NSClassFromString("UITabBarButton")
        
        var index = 0
        
        for view in subviews {
            
            if view.isKindOfClass(cls!) {
                // 相对于原始frame的偏移量
                view.frame = CGRectOffset(originFrame, width * CGFloat(index), 0)
                
                index += index == 1 ? 2 : 1
            }
        }
        composeBtn.frame = CGRect(x: width * 2, y: 0, width: width, height: frame.height)
    }
    
    private lazy var composeBtn: UIButton = {
        
        let button = UIButton()
        
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Selected)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Selected)
        
        button.addTarget(self, action: "composeBtnDidClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        self.addSubview(button)
        
        return button
    }()
    // 在tabBar中设置闭包
    func composeBtnDidClick() {
    
        composeClosure?()
    }

}
